package zl.ordermanager.service.impl;

import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import zl.ordermanager.utils.MD5Util;
import zl.ordermanager.vo.DataGrid;
import zl.ordermanager.vo.ERoles;
import zl.ordermanager.vo.PageHelper;
import zl.ordermanager.vo.SessionInfo;
import zl.ordermanager.vo.User;
import zl.ordermanager.dao.UserDao;
import zl.ordermanager.po.Tuser;
import zl.ordermanager.service.UserService;

@Service
public class UserServiceImpl implements UserService {

	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(UserServiceImpl.class);

	@Autowired
	private UserDao userDao;

	@Override
	@Transactional
	public User login(User user) {
		if (logger.isDebugEnabled()) {
			logger.debug("login(User) - start");
		}

		Map<String, Object> params = new HashMap<String, Object>();
		params.put("username", user.getUsername());
		params.put("password", MD5Util.getMD5(user.getPassword()));
		Tuser tuser = userDao.get("from Tuser t where t.username = :username and t.password = :password", params);
		if (tuser != null) {
			BeanUtils.copyProperties(tuser, user);

			if (logger.isDebugEnabled()) {
				logger.debug("login(User) - end");
			}
			return user;
		}

		if (logger.isDebugEnabled()) {
			logger.debug("login(User) - end");
		}
		return null;
	}

	@Override
	public DataGrid<User> dataGrid(PageHelper pageHelper) {
		DataGrid<User> dataGrid = new DataGrid<User>();
		List<User> listUser = new ArrayList<User>();
		Map<String, Object> params = new HashMap<String, Object>();
		if (pageHelper.getKeywords() != null && !pageHelper.getKeywords().isEmpty()) {
			params.put("keyword", "%%" + pageHelper.getKeywords() + "%%");
		}
		String hql = " from Tuser t where t.username!='admin' ";
		List<Tuser> listTuser = userDao.find(hql + whereHql(pageHelper) + orderHql(pageHelper), params,
				pageHelper.getPageNum(), pageHelper.getNumPerPage());
		if (listTuser != null && listTuser.size() > 0) {
			for (Tuser tuser : listTuser) {
				User user = new User();
				BeanUtils.copyProperties(tuser, user);
				listUser.add(user);
			}
		}
		dataGrid.setList(listUser);
		dataGrid.setTotal(userDao.count("select count(*) " + hql + whereHql(pageHelper), params));
		return dataGrid;
	}

	private String whereHql(PageHelper pageHelper) {
		String whereString = "";
		if (pageHelper.getKeywords() != null && !pageHelper.getKeywords().isEmpty()) {
			whereString += " and (t.username like :keyword ";
			whereString += " or t.realname like :keyword ";
			whereString += " or t.role like :keyword) ";
		}
		return whereString;
	}

	private String orderHql(PageHelper pageHelper) {
		String orderString = "";
		if (pageHelper.getOrderField() != null && !pageHelper.getOrderField().isEmpty()
				&& pageHelper.getOrderDirection() != null && !pageHelper.getOrderDirection().isEmpty()) {
			orderString = " order by t." + pageHelper.getOrderField() + " " + pageHelper.getOrderDirection();
		}
		return orderString;
	}

	@Override
	public User get(Integer id) {
		Tuser tuser = userDao.get(Tuser.class, id);
		if (tuser == null) {
			return null;
		}
		User user = new User();
		BeanUtils.copyProperties(tuser, user);
		return user;
	}

	@Override
	public User getByUsername(String username) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("username", username);
		String hql = "from Tuser t where t.username = :username";
		Tuser tuser = userDao.get(hql, params);
		if (tuser != null) {
			User user = new User();
			BeanUtils.copyProperties(tuser, user);
			return user;
		}
		return null;
	}

	@Override
	public void add(User user) throws Exception {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("username", user.getUsername());
		if (userDao.count("select count(*) from Tuser t where t.username = :username", params) > 0) {
			throw new Exception("用户名已存在！");
		} 
		Tuser tuser = new Tuser();
		BeanUtils.copyProperties(user, tuser);
		if (tuser.getPassword() == null || tuser.getPassword().isEmpty()) {
			tuser.setPassword(MD5Util.getMD5("123456"));
		}
		userDao.save(tuser);
	}

	@Override
	public void edit(User user) throws Exception {
		Tuser tuser = userDao.get(Tuser.class, user.getId());
		String oldPassword = tuser.getPassword();
		BeanUtils.copyProperties(user, tuser);
		if (!user.getPassword().equals(oldPassword)) {
			tuser.setPassword(MD5Util.getMD5(user.getPassword()));
		}
	}

	@Override
	public void delete(Integer id) {
		userDao.delete(userDao.get(Tuser.class, id));
	}

	@Override
	public boolean editCurUserPwd(SessionInfo sessionInfo, String oldPwd, String pwd) {
		Tuser tuser = userDao.get(Tuser.class, sessionInfo.getId());
		if (tuser.getPassword().equals(MD5Util.getMD5(oldPwd))) {
			tuser.setPassword(MD5Util.getMD5(pwd));
			return true;
		} else {
			return false;
		}
	}

	@Override
	public List<User> getList(ERoles role) {
		List<User> listUser = new ArrayList<User>();
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("role", role.getRole());
		String hql = " from Tuser t where t.role = :role ";
		List<Tuser> listTuser = userDao.find(hql, params);
		if (listTuser != null && listTuser.size() > 0) {
			for (Tuser tuser : listTuser) {
				User user = new User();
				BeanUtils.copyProperties(tuser, user);
				listUser.add(user);
			}
		}
		
		return listUser;
	}

}
